﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

using WalburySoftware;

namespace Gigamud
{
    internal class ConnectionController
    {

        private TerminalControl _terminalControl;

        public event EventHandler<WalburySoftware.TerminalControl.TerminalEventArgs> OnDisconnect;
        public event EventHandler<WalburySoftware.TerminalControl.TerminalEventArgs> NewChar;

        public ConnectionController(TerminalControl Terminal)
        {
            _terminalControl = Terminal;
        }

        internal bool Connect(string host)
        {
            _terminalControl.Host = host;
            _terminalControl.Method = WalburySoftware.ConnectionMethod.Telnet;

            try
            {
                _terminalControl.Connect();
            }
            catch (SystemException e)
            {
                throw e;
            }

            _terminalControl.SetPaneColors(Color.Gray, Color.Black);
            _terminalControl.Focus();
            _terminalControl.OnDisconnect += new EventHandler<WalburySoftware.TerminalControl.TerminalEventArgs>(TermCtrl_OnDisconnect);
            _terminalControl.OnUpdate += new EventHandler<WalburySoftware.TerminalControl.TerminalEventArgs>(TermCtrl_OnUpdate);
            _terminalControl.OnNewChar += new EventHandler<WalburySoftware.TerminalControl.TerminalEventArgs>(TermCtrl_OnNewChar);
            return true;
        }

        internal void Disconnect(string reason)
        {
            _terminalControl.Close();
            char[] msg1 = reason.ToCharArray();
            OnDisconnect(this, new WalburySoftware.TerminalControl.TerminalEventArgs(msg1, null));
        }

        internal void SendText(string TextToSend)
        {
            _terminalControl.SendText(TextToSend);
        }

        private void TermCtrl_OnDisconnect(object sender, WalburySoftware.TerminalControl.TerminalEventArgs args)
        {
            OnDisconnect(this, args);
        }

        private void TermCtrl_OnUpdate(object sender, WalburySoftware.TerminalControl.TerminalEventArgs args)
        {
        }

        private void TermCtrl_OnNewChar(object sender, WalburySoftware.TerminalControl.TerminalEventArgs args)
        {
            NewChar(this, args);
        }
    }
}
